package tcm.com.gistone.api.restController;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.api.service.SectionService;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.EdatResult;
import tcm.com.gistone.util.Item;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * Created by wangfan on 2017/7/22.
 */
@RestController("apiReaderController")
@RequestMapping("api/reader")
public class ReaderController {
    @Autowired
    private GetBySqlMapper getBySqlMapper;
    @Autowired
    private SectionService sectionService;
    /**
     * 获取item节点的所有后节点信息
     *
     * @param bookId
     * @param item
     * @return
     */
    private Item childNode(int bookId, Item item) {
        List<Item> nodes = nodes(bookId, item);
        if (nodes.size() > 0) {
            item.setLeaf(false);

            for (Item node : nodes) {

                childNode(bookId, node);

            }
            item.setNodes(nodes);

        } else {
            item.setLeaf(true);
        }

        return item;
    }

    /**
     * 获取当前节点的下一级节点信息
     *
     * @param bookId
     * @param item
     * @return
     */
    private List<Item> nodes(int bookId, Item item) {
        List<Item> nodes = new ArrayList<>();
        long id = item.getId();
        String sql = "select * from tb_directory where id !=parent_id and book_id =" + bookId + " and parent_id=" + id;
        List<Map> childList = this.getBySqlMapper.findRecords(sql);
        if (childList.size() > 0) {

            for (Map map : childList) {
                Item child = new Item();
                child.setId((long) map.get("id"));
                child.setText(map.get("name").toString());
                Object secId = map.get("section_id");
                if (secId != null) {
                    child.setSectionId(Integer.parseInt(map.get("section_id") == null ? "" : map.get("section_id").toString()));
                    String sql2 = "select number from tb_section where section_id =" + child.getSectionId();


                    child.setNumber(this.getBySqlMapper.findNumber(sql2));
                }

                nodes.add(child);
            }

        }
        return nodes;
    }


    /**
     * 获取bootstrap treeview 的data信息
     *
     * @return
     */
    @RequestMapping(value = "getTree", method = RequestMethod.GET)
    public EdatResult getTree(HttpServletResponse response, HttpServletRequest request) {
//        ClientUtil.SetCharsetAndHeader(request, response);
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            int bookId = data.getInt("bookId");
            List<Item> voItemList = new ArrayList<Item>();
            Item root = new Item();
            String sql = "select * from tb_directory where book_id =" + bookId+" and level =0";
            String bookName = this.getBySqlMapper.findRecords(sql).get(0).get("name").toString();
            root.setText(bookName);
            root.setId((long)this.getBySqlMapper.findRecords(sql).get(0).get("id"));
            root.setLeaf(false);
            childNode(bookId, root);
            voItemList.add(root);
    //        return voItemList;
            return EdatResult.ok(voItemList);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }



/*    @RequestMapping(value = "getContent", method = RequestMethod.GET)
    public String getContent(@RequestParam Integer bookId) {

        String content = "";
        String sql = "select * from tb_section where book_id =" + bookId;
        List<Map> maps = this.getBySqlMapper.findRecords(sql);

        for (int i = 0; i < maps.size(); i++) {

            Map map = maps.get(i);
            String section = map.get("section_content").toString();
            Pattern p = Pattern.compile("\\s{21}");
            Matcher m = p.matcher(section);
            section = m.replaceAll("");

            section = section.replace("      ", "<br/>&#12288;&#12288;");
            section = section.replaceAll("\r\n", "<br/>");
            section = section.replaceAll("\r", "<br/>");

            if (i == maps.size() - 1) {
                content = content + "&#12288;&#12288;" + section;
            } else {

                content = content + "&#12288;&#12288;" + section + "<br/>";
            }
        }
        return content;
    }*/

    @RequestMapping(value = "getContentByNumber", method = RequestMethod.GET)
    public EdatResult getContentByNumber(HttpServletRequest request,
                                         HttpServletResponse response) {
        Map result =new HashMap();
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            int bookId = data.getInt("bookId");
            int number = data.getInt("number");
            Integer sectionId = null;
            if (data.has("sectionId")) {
                sectionId = data.getInt("sectionId");

            }
            String content = "";
            String sql = "select * from tb_section where book_id =" + bookId + " and number =" + number;
            List<Map> maps = this.getBySqlMapper.findRecords(sql);
            if(null!=sectionId){
                result.put("sectionId",sectionId);


            }
            for (int i = 0; i < maps.size(); i++) {

                Map map = maps.get(i);
                String sectionTitle = map.get("section_title").toString();
                if(null==sectionId){
                    if(i==0){
                        result.put("sectionId",map.get("section_id").toString());
                    }


                }

//                String[] arr = sectionTitle.split("/");
//                sectionTitle =arr[arr.length-1];

                String section = map.get("section_content").toString();
              /*  Pattern p = Pattern.compile("\\s{21}");
                Matcher m = p.matcher(section);
                section = m.replaceAll("");*/
                section = section.replaceAll("\r\n", "<br/>");
                section = section.replaceAll("\r", "<br/>");
                section = section.replaceAll("\n", "<br/>");
                section = section.replaceAll("      ", "<br/>&#12288;&#12288;");
                section = section.replaceAll("    ", "<br/>&#12288;&#12288;");



                if (i == maps.size() - 1) {
                    if (null != sectionId && sectionId .equals(Integer.valueOf(map.get("section_id").toString()))) {
                        content = content + "<span class='selective'>" + sectionTitle + "</span>" + "<br/>&#12288;&#12288;" + section;

                    } else {
                        content = content + "<span class='sectionTitle'>" + sectionTitle + "</span>" + "<br/>&#12288;&#12288;" + section;
                    }
                } else {

                    if (null != sectionId && sectionId .equals(Integer.valueOf(map.get("section_id").toString())))  {
                        content = content + "<span class='selective'>" +  sectionTitle + "</span>" + "<br/>&#12288;&#12288;" + section + "<br/>";
                    } else {
                        content = content + "<span class='sectionTitle'>" + sectionTitle + "</span>" + "<br/>&#12288;&#12288;" + section + "<br/>";
                    }


                }
                content=getMapHighlight(content);

            }
            sql = "select * from tb_bookinfo where  status=7 and book_id =" + bookId ;
            List<Map> m = this.getBySqlMapper.findRecords(sql);

            result.put("bookName",m.get(0).get("book_name"));

            result.put("content",content);
            result.put("imgUrl",sectionService.getImgUrlById(Long.valueOf(result.get("sectionId").toString())));



            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }

    }


    @RequestMapping(value = "getBookInfo", method = RequestMethod.GET)
    public Map getBookInfo(@RequestParam Integer bookId) {
        Map map = new HashMap();
        String sql = "select * from tb_bookinfo where status=7 and book_id =" + bookId;
        map.put("bookInfo", this.getBySqlMapper.findRecords(sql).get(0));


        sql = "select max(number) as number from tb_section where book_id =" + bookId;

        map.put("pagenum", this.getBySqlMapper.findrows(sql));

        return map;
    }

    private  String getMapHighlight(String content){
        String sql = "select DISTINCT (ancient) from tb_ancient_modern_place;";
        List<Map> rs = this.getBySqlMapper.findRecords(sql);
        for (Map r : rs) {
            String ancient =r.get("ancient").toString().replaceAll(" ","");
            content=content.replaceAll(ancient,"<span class='ancientPlace'>" + ancient + "</span>");


        }
        return  content;


    }

    @RequestMapping(value = "getModernPlace", method = RequestMethod.GET)
    public EdatResult getModernPlace(HttpServletRequest request,
                                         HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String ancient = data.getString("ancient");
            System.out.println(ancient);
            String sql = "select * from tb_ancient_modern_place where ancient ='" + ancient+"'";


           List<Map> results = this.getBySqlMapper.findRecords(sql);

           List<String> places =new ArrayList<>();

            for (Map result : results) {
                String modern =result.get("modern").toString();
                String[] arr=modern.split("、");
                for (String s : arr) {
                    if(!places.contains(s.trim())){
                        places.add(s.trim());
                    }


                }

            }
            return EdatResult.ok(places);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }


    }



}
